package com.qing.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.eduservice.entity.pojo.EduCourse;
import com.qing.eduservice.entity.pojo.EduCourseDescription;
import com.qing.eduservice.entity.pojo.EduTeacher;
import com.qing.eduservice.entity.pojo.EduVideo;
import com.qing.eduservice.entity.vo.*;
import com.qing.eduservice.mapper.EduCourseDescriptionMapper;
import com.qing.eduservice.mapper.EduCourseMapper;
import com.qing.eduservice.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.servicebase.exception.JsonException;
import com.qing.servicebase.utils.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Yjx
 * @since 2022-09-08
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    private final EduCourseDescriptionService eduCourseDescriptionService;
    private final EduCourseMapper eduCourseMapper;
    private final EduVideoService eduVideoService;
    private final EduChapterService eduChapterService;
    private final EduTeacherService eduTeacherService;

    public EduCourseServiceImpl(EduCourseDescriptionService eduCourseDescriptionService,
                                EduCourseMapper eduCourseMapper,
                                EduVideoService eduVideoService,
                                EduChapterService eduChapterService,
                                EduTeacherService eduTeacherService) {
        this.eduCourseDescriptionService = eduCourseDescriptionService;
        this.eduCourseMapper = eduCourseMapper;
        this.eduVideoService = eduVideoService;
        this.eduChapterService = eduChapterService;
        this.eduTeacherService = eduTeacherService;
    }

    @Override
    public ResponseResult saveCourseInfo(CourseInfoVo courseInfoVo) {
        //保存课程基本信息
        EduCourse course = new EduCourse();
        course.setStatus(EduCourse.COURSE_DRAFT);
        BeanUtils.copyProperties(courseInfoVo, course);
        boolean resultCourseInfo = this.save(course);
        if (!resultCourseInfo) {
            throw new JsonException(201, "课程信息保存失败");
        }
        //保存课程详情信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());

        courseDescription.setId(course.getId());
        boolean resultDescription = eduCourseDescriptionService.save(courseDescription);
        if (!resultDescription) {
            throw new JsonException(201, "课程详情信息保存失败");
        }
        return ResponseResult.ofSuccess(course.getId());
    }

    @Override
    public ResponseResult getCourseInfoFormById(String id) {
        EduCourse course = this.getById(id);
        if (course == null) {
            throw new JsonException(201, "数据不存在");
        }
        CourseInfoVo courseInfoForm = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoForm);
        EduCourseDescription courseDescription = eduCourseDescriptionService.getById(id);
        if (course != null) {
            courseInfoForm.setDescription(courseDescription.getDescription());
        }
        return ResponseResult.ofSuccess(courseInfoForm);
    }

    @Override
    public ResponseResult updateCourseInfoById(CourseInfoVo courseInfoVo) {
        //保存课程基本信息
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        boolean resultCourseInfo = this.updateById(course);
        if (!resultCourseInfo) {
            throw new JsonException(201, "课程信息保存失败");
        }
//保存课程详情信息
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(course.getId());
        boolean resultDescription =
                eduCourseDescriptionService.updateById(courseDescription);
        if (!resultDescription) {
            throw new JsonException(201, "课程详情信息保存失败");
        }
        return ResponseResult.ofSuccess(null);
    }

    @Override
    public ResponseResult getCoursePublishVoById(String id) {
        CoursePublishVo coursePublishVo = eduCourseMapper.selectCoursePublishVoById(id);
        return coursePublishVo != null ? ResponseResult.ofSuccess(coursePublishVo)
                : ResponseResult.ofException(new JsonException(201, "操作失败"));
    }

    @Override
    public ResponseResult publishCourseById(String id) {
        EduCourse course = new EduCourse();
        course.setId(id);
        course.setStatus(EduCourse.COURSE_NORMAL);
        Integer count = baseMapper.updateById(course);
        return ResponseResult.ofSuccess(null != count && count > 0);
    }

    @Override
    public ResponseResult pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");
        if (courseQuery == null) {
            baseMapper.selectPage(pageParam, queryWrapper);
            return ResponseResult.ofException(new JsonException(201,"操作失败"));
        }
        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            queryWrapper.eq("teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.ge("subject_parent_id", subjectParentId);
        }
        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.ge("subject_id", subjectId);
        }
        IPage<EduCourse> eduCourseIPage = baseMapper.selectPage(pageParam, queryWrapper);
        return ResponseResult.ofSuccess(eduCourseIPage);
    }

    @Override
    public ResponseResult removeByCourseId(String courseId) {
        //根据id删除所有视频
        eduVideoService.removeByCourseId(courseId);
        //根据id删除所有章节
        eduChapterService.removeByCourseId(courseId);
        //根据id删除所有课程详情
        eduCourseDescriptionService.removeById(courseId);

        Integer result = baseMapper.deleteById(courseId);
        return ResponseResult.ofSuccess(null != result && result > 0);
    }

    @Override
    public ResponseResult selectByTeacherId(String teacherId) {
        //查询讲师信息
        EduTeacher teacherById = eduTeacherService.getById(teacherId);

        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<EduCourse>();
        queryWrapper.eq("teacher_id", teacherById.getId());
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");
        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("teacher",teacherById);
        map.put("courseList",courses);
        return courses!=null?ResponseResult.ofSuccess(map):
                ResponseResult.ofException(new JsonException(201,"操作失败"));
    }

    @Override
    public ResponseResult pageListWeb(Page<EduCourse> pageParam, CourseQueryVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id",
                    courseQuery.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }
        baseMapper.selectPage(pageParam, queryWrapper);
        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        System.out.println(map);
        return map!=null?ResponseResult.ofSuccess(map):
                ResponseResult.ofException(new JsonException(201,"操作失败"));
    }

    @Override
    public ResponseResult selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        CourseWebVo courseWebVo = baseMapper.selectInfoWebById(id);
        return ResponseResult.ofSuccess(courseWebVo);
    }

    @Override
    public ResponseResult updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        int i = baseMapper.updateById(course);
        return i>0?ResponseResult.ofSuccess("操作成功"):
                ResponseResult.ofException(new JsonException(201,"操作失败"));
    }
}
